<template>
  <div class="admin-manage">
    <el-tabs type="card">
      <!--管理员管理-->
      <el-tab-pane>
        <span slot="label">
          <i class="fa fa-money"></i> 管理员设置
        </span>
        <el-form :inline="true" size="mini" style="margin-left: 10px" class="search-form">
          <el-form-item label="姓名">
            <el-input v-model="search.name"></el-input>
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input v-model="search.loginName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="button" icon="el-icon-tickets" @click="showAll()">显示全部</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-plus" @click="showAddDialog=true">新增</el-button>
          </el-form-item>
        </el-form>
        <el-table
          size="mini"
          :data="adminList|filterAdmin(search.name,search.loginName)"
          style="width: 100%"
          :height="getTableHeight()"
        >
          <el-table-column fixed prop="name" label="姓名"></el-table-column>
          <el-table-column prop="phone" label="登录账号"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">{{scope.row.status==='ENABLE'?'可用':'禁用'}}</template>
          </el-table-column>
          <el-table-column label="角色">
            <template slot-scope="scope">{{getRoleString(scope.row.roles)}}</template>
          </el-table-column>
          <el-table-column>
            <template slot="header" slot-scope="scope">
              <div style="text-align: center;width: 70%">操作</div>
            </template>
            <template slot-scope="scope">
              <a
                class="t-link"
                @click="_updateStatus(scope.row)"
              >{{scope.row.status==='ENABLE'?'禁用':'启用'}}</a>
              <a class="t-link" @click="_resetpwd(scope.row)">重置密码</a>
              <a class="t-link" @click="(showAdminPerformance=true)&&(selectedAdmin=scope.row)">查看绩效</a>
              <a class="t-link" @click="toAssginRoleForAdmin(scope.row)">分配角色</a>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <!-- 系统角色管理 -->
      <el-tab-pane>
        <span slot="label">
          <i class="fa fa-money"></i> 系统角色设置
        </span>
        <el-button type="primary" size="mini" icon="fa fa-icon-plus" @click="toEditSysRole()">新增角色</el-button>
        <el-table :data="sysRoleList" size="mini" :height="getTableHeight()">
          <el-table-column label="角色名" prop="roleName"></el-table-column>
          <el-table-column label="描述" prop="description"></el-table-column>
          <el-table-column label="权限">
            <template slot-scope="scope">
              <div v-if="scope.row.editing">
                <el-select
                  v-model="scope.row.permissions"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择文章标签"
                >
                  <el-option
                    v-for="item in sysPermissions"
                    :key="item.permissionId"
                    :label="item.permissionName"
                    :value="item.permissionId"
                  ></el-option>
                </el-select>
              </div>
              <div v-else>
                <span
                  class="permissionItem"
                  v-for="item in scope.row.permissions"
                >{{item.permissionName}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <a class="t-link" @click="deleteRole(scope.row)">删除</a>
              <a class="t-link" @click="toSelectPermissions(scope.row)">分配权限</a>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <el-dialog title="新增管理员" :visible.async="showAddDialog" :show-close="false">
      <el-form ref="adminForm" :model="adminEdit">
        <el-form-item prop="name" :rules="[{required:true,message:'用户名不能为空'}]">
          <el-input type="name" placeholder="请输入" v-model="adminEdit.name">
            <template slot="prepend">用户姓名</template>
          </el-input>
        </el-form-item>
        <el-form-item prop="loginName" :rules="[{required:true,message:'登录账号不能为空'}]">
          <el-input type="loginName" placeholder="请输入" v-model="adminEdit.loginName">
            <template slot="prepend">登录账号</template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password" :rules="[{required:true,message:'密码不能为空'}]">
          <el-input placeholder="请输入" type="password" v-model="adminEdit.password">
            <template slot="prepend">
              密
              <span style="visibility: hidden">啊啊</span>码
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="confirmPass"
          :rules="[{required:true,message:'密码不能为空'},{validator: validatePass.bind(adminEdit) , trigger: 'blur' }]"
        >
          <el-input placeholder="请输入" type="confirmPass" v-model="adminEdit.confirmPass">
            <template slot="prepend">确认密码</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddDialog = false">取 消</el-button>
        <el-button type="primary" @click="addAdmin()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="showOperationDialog" width="30%">
      <span>{{operationTip}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showOperationDialog = false">取 消</el-button>
        <el-button type="primary" @click="doOperation()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="管理员绩效" :visible.sync="showAdminPerformance" width="50%">
      <performance :admin="selectedAdmin"></performance>
    </el-dialog>
    <!-- 新增系统角色对话框 -->
    <el-dialog title="新增系统角色" :visible.sync="sysRoleEditDialogVisible" width="60%">
      <el-form ref="sysRoleEdit" :model="sysRoleEdit">
        <el-form-item prop="roleName" label="角色名" :rules="[{required:true,message:'角色名不能为空'}]">
          <el-input type="roleName" placeholder="请输入" v-model="sysRoleEdit.roleName"></el-input>
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input type="description" placeholder="请输入" v-model="sysRoleEdit.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sysRoleEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="newSysRole()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 权限分配框 -->
    <el-dialog title="权限分配" :visible.sync="showPermissionDialog" width="60%">
      <div class="transfer-container">
        <el-transfer v-model="selectedPermissions" :data="sysPermissions" :titles="['权限列表','已选择']"></el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showPermissionDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="updateRolePermission()"
          v-if="selectedPermissions.length"
        >确 定</el-button>
      </div>
    </el-dialog>
    <!-- 角色分配框 -->
    <el-dialog title="角色分配" :visible.sync="showRoleAssignDialog" width="60%">
      <div class="transfer-container">
        <el-transfer
          v-model="selectedRoles"
          :data="getTranferRoleList(sysRoleList)"
          :titles="['角色列表','已分配']"
        ></el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showRoleAssignDialog = false">取 消</el-button>
        <el-button type="primary" @click="assignRoleForAdmin()" v-if="selectedRoles.length">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import Performance from './performance'
import * as adminManageApi from '@/api/admin_manage'
import { SUCCESS_CODE, OP_SUCCESS, OP_FAIL } from '@/config/config'

export default {
  name: 'admin_manage',
  components: { Performance },
  data: function() {
    return {
      showAddDialog: false,
      showOperationDialog: false,
      showAdminPerformance: false,
      showPermissionDialog: false,
      showRoleAssignDialog: false,
      selectedPermissions: [],
      selectedRole: null,
      selectedRoles: [],
      operationTip: '',
      operation: '',
      selectedAdmin: null,
      validatePass: function(rule, value, callback) {
        if (value !== this.password) {
          callback(new Error('两次输入的密码不一致！'))
        } else {
          callback()
        }
      },
      sysRoleEditDialogVisible: false,
      sysRoleList: [], // 系统角色列表
      sysPermissions: [], // 系统权限列表
      sysRoleEdit: {
        roleName: '',
        description: '',
        permissions: []
      }
    }
  },
  computed: {
    ...mapState('adminManage', ['adminList', 'search', 'adminEdit'])
  },
  methods: {
    ...mapActions('adminManage', [
      'fetchAdminList',
      'newAdmin',
      'updateStatus',
      'resetAdminPwd'
    ]),
    handleSearch: function() {
      this.fetchAdminList().then(function() {
        console.log(arguments)
      })
    },
    /**
     * 更改管理员状态
     * @param admin
     */
    _updateStatus: function(admin) {
      this.showOperationDialog = true
      this.operation = 'updateStatus'
      this.selectedAdmin = admin
      this.operationTip = `确定要 ${
        admin.status === 'ENABLE' ? '禁用' : '启用'
      }管理员"${admin.name}"吗？`
    },
    /**
     * 重置管理员密码
     * @param admin
     */
    _resetpwd: function(admin) {
      this.showOperationDialog = true
      this.operation = 'resetPass'
      this.selectedAdmin = admin
      this.operationTip = `确定要为管理员"${admin.name}"重置密码吗？`
    },
    doOperation: function() {
      if (this.operation === 'updateStatus') {
        this.updateStatus(this.selectedAdmin).then(data => {
          this.fetchAdminList()
        })
      }
      if (this.operation === 'resetPass') {
        this.resetAdminPwd(this.selectedAdmin.id).then(data => {
          this.fetchAdminList()
        })
      }
      this.showOperationDialog = false
    },
    /**
     * 新增管理员
     */
    addAdmin: function() {
      this.$refs['adminForm'].validate(valid => {
        if (valid) {
          this.newAdmin(this.adminEdit).then(data => {
            console.log(data)
            this.showAddDialog = false
            this.fetchAdminList()
          })
        }
      })
    },
    showAll: function() {
      this.search.name = ''
      this.search.loginName = ''
    },
    /** *******************管理员相关方法************************** */
    toAssginRoleForAdmin(selectedAdmin) {
      this.selectedRoles.length = 0
      selectedAdmin.roles.forEach(role => {
        this.selectedRoles.push(role.roleId)
      })
      this.selectedAdmin = selectedAdmin
      this.showRoleAssignDialog = true
    },
    // 为管理员分配角色
    assignRoleForAdmin() {
      console.log(this.selectedAdmin)
      adminManageApi
        .assignUserRole(this.selectedAdmin.id, this.selectedRoles.join(','))
        .then(resp => {
          let data = resp.data
          this.handleOpSuccess(data)
          this.showRoleAssignDialog = false
          this.fetchAdminList()
          this.selectedRoles = []
        })
    },
    /** *******************角色权限相关方法************************ */
    // 获取角色列表
    getSysRoleList() {
      adminManageApi.getSysRoleList().then(resp => {
        let data = resp.data
        this.sysRoleList = data.data
      })
    },
    // 为 el-transfer 准备角色显示数据
    getTranferRoleList(roleList) {
      return roleList.map(role => {
        return { key: role.roleId, label: role.roleName }
      })
    },
    // 删除角色
    deleteRole(role) {
      this.$swal
        .fire({
          title: `你确定要删除该角色"${role.roleName}"吗？`,
          type: 'info',
          allowOutsideClick: false
        })
        .then(yes => {
          if (yes) {
            adminManageApi.deleteRole(role.roleId).then(resp => {
              let data = resp.data
              this.handleOpSuccess(data)
              this.getSysRoleList()
            })
          }
        })
    },
    // 打开系统角色编辑对话框
    toEditSysRole() {
      this.sysRoleEditDialogVisible = true
    },
    // 新建系统角色
    newSysRole() {
      this.$refs['sysRoleEdit'].validate(valid => {
        if (valid) {
          adminManageApi
            .newSysRole(this.sysRoleEdit.roleName, this.sysRoleEdit.description)
            .then(resp => {
              let data = resp.data
              this.handleOpSuccess(data)
              this.getSysRoleList()
              this.sysRoleEditDialogVisible = false
            })
        }
      })
    },
    // 去编辑角色权限
    toSelectPermissions(selectedRole) {
      this.selectedPermissions.length = 0
      selectedRole.permissions.forEach(permission => {
        this.selectedPermissions.push(permission.permissionId)
      })
      this.showPermissionDialog = true
      this.selectedRole = selectedRole
    },
    // 更新角色权限
    updateRolePermission() {
      adminManageApi
        .updateRole(
          this.selectedRole.roleId,
          this.selectedPermissions.join(',')
        )
        .then(resp => {
          let data = resp.data
          this.handleOpSuccess(data)
          this.showPermissionDialog = false
          this.getSysRoleList()
        })
    },
    getRoleString(roles) {
      return roles.map(role => role.roleName).join(',')
    }
  },
  created() {
    this.fetchAdminList()
    this.getSysRoleList()
    adminManageApi.getPermissionList().then(resp => {
      let data = resp.data
      data.data.forEach(permission => {
        this.sysPermissions.push({
          key: permission.permissionId,
          label: permission.permissionName
        })
      })
    })
  },
  filters: {
    filterAdmin: function(value, searchName, searchLoginName) {
      let result = value
      if (searchName) {
        result = result.filter(item => item.name.indexOf(searchName) !== -1)
      }
      if (searchLoginName) {
        result = result.filter(
          item => item.phone.indexOf(searchLoginName) !== -1
        )
      }
      return result
    }
  }
}
</script>

<style>
.admin-manage .search-form .el-form-item {
  margin-bottom: 0;
}
.permissionItem {
  padding: 1px 2px;
  color: grey;
  text-decoration: underline;
}
.permissionEditLink {
  padding: 3px 2px;
}
.transfer-container {
  display: flex;
  display: -webkit-flex;
  align-items: center;
  -webkit-align-items: center;
  justify-content: center;
  -webkit-justify-content: center;
}
</style>
